<?php


namespace app\controller;


use app\model\ViidDeviceRelate;
use fast\Tree;
use think\facade\Db;

class ViidDeviceType extends BackendController{
    protected $model = null;
    public function _initialize()
    {
        //parent::_initialize();
        $this->model = new \app\model\ViidDeviceType();

    }

    public function index() {
        $list = $this->model->select();
        $tree = Tree::instance();
        $tree->init(collection($list)->toArray(), 'pid');
        $list = $tree->getTreeArray(0);
        unset($item);
        $data = [
            'code'  => 0,
            'msg'   => '',
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * 分类下添加小区
     * @param string $device_ids
     * @param string $type_ids
     * @return void
     */
    public function add_device($device_ids,$type_ids){
        $device_ids=explode(",",$device_ids);
        $type_ids=explode(",",$type_ids);
        $list = $this->model->select();
        $tree = Tree::instance();
        $tree->init(collection($list)->toArray(), 'pid');
        Db::startTrans();
        try {
            foreach ($type_ids as $type_id) {
                $all=[];
                $single['type_id']=$type_id;
                foreach ($device_ids as $device_id) {
                    $single['device_id']=$device_id;
                    $all[]=$single;
                }
                $this->model->addChildren($all,$tree->getParentsIds($type_id,true));
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('新增成功');
    }

}